package netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


/**
 * @Author: zhangrongqing
 * @Date: 2019/12/10 19:18
 */
public class NettyServer {
    public static void main(String[] args) {
        EventLoopGroup parentGroup = new NioEventLoopGroup();  //主线程
        EventLoopGroup childGroup = new NioEventLoopGroup();   //worker线程
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();   //服务类
            serverBootstrap.group(parentGroup, childGroup);     //线程池
            serverBootstrap.channel(NioServerSocketChannel.class);          //设置socket工厂
            //option设置tcp的参数
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 2048)    //设置缓冲池的大小
                    .childOption(ChannelOption.SO_KEEPALIVE, true)        //设置连接数活跃
                    .childOption(ChannelOption.TCP_NODELAY, true)        //关闭延迟发送
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new StringDecoder());   //解码器
                            socketChannel.pipeline().addLast(new StringEncoder());   //编码器
//                            socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter());     //自定义处理器
                            socketChannel.pipeline().addLast(new SimpleHandler());
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(8090).sync();  //绑定端口
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }

    }
}
